package scatter.captcha.rest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.Ordered;
import scatter.captcha.rest.filter.CaptchaPreventFilter;
import scatter.captcha.rest.filter.PatternConfigProperties;
import scatter.captcha.rest.service.ICaptchaBgImageRandomService;
import scatter.captcha.rest.service.ICaptchaPreventStoreService;
import scatter.captcha.rest.service.ICaptchaStoreService;
import scatter.captcha.rest.service.impl.DefaultCaptchaBgImageRandomServiceImpl;
import scatter.captcha.rest.service.impl.DefaultCaptchaPreventStoreServiceImpl;
import scatter.captcha.rest.service.impl.DefaultCaptchaStoreServiceImpl;

/**
 * <p>
 *
 * </p>
 *
 * @author yangwei
 * @since 2020-11-10 22:41
 */
@ComponentScan
@Slf4j
public class CaptchaConfiguration {
    /**
     * controller访问基础路径
     */
    public static final String CONTROLLER_BASE_PATH = "";
    /**
     * FeignClient
     */
    public static final String FEIGN_CLIENT = "captcha";

    /**
     * 默认验证码存储服务
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public ICaptchaStoreService iCaptchaStoreService(){
        return new DefaultCaptchaStoreServiceImpl();
    }

    /**
     * 默认验证码阻止存储服务
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public ICaptchaPreventStoreService iCaptchaPreventStoreService(){
        return new DefaultCaptchaPreventStoreServiceImpl();
    }

    /**
     * 默认获取验证码背景图服务
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public ICaptchaBgImageRandomService iCaptchaBgImageRandomService(){
        return new DefaultCaptchaBgImageRandomServiceImpl();
    }

    /**
     * 验证码阻止过滤器
     * @return
     */
    @Bean
    public CaptchaPreventFilter captchaPreventFilter(){
        return new CaptchaPreventFilter();
    }

    /**
     * 验证码阻止过滤器注入 顺序仅将于链路跟踪过滤器
     * @param captchaPreventFilter
     * @return
     */
    @Bean
    public FilterRegistrationBean captchaFilterBean(CaptchaPreventFilter captchaPreventFilter,PatternConfigProperties patternConfigProperties) {
        FilterRegistrationBean registration = new FilterRegistrationBean(captchaPreventFilter);
        if (patternConfigProperties.getPreventConfigs() != null) {
            for (PatternConfigProperties.CaptchaPreventConfig preventConfig : patternConfigProperties.getPreventConfigs()) {
                registration.addUrlPatterns(preventConfig.getPurpose());
            }
        }
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 10);
        return registration;
    }
}
